package service

import (
    "encoding/json"
    "errors"
    
    "gorm.io/gorm"
    
    "collecter/app/common/enum"
    "collecter/app/common/helper"
    "collecter/app/model"
)

type CollectService struct {
    Id          int64
    UserId      int64
    CategoryId  int64
    Title       string
    Description string
    Content     string
    ContentType int8
}

func NewCollectService() *CollectService {
    return &CollectService{}
}

func (cs *CollectService) Create() error {
    if cs.CategoryId == 0 {
        category := model.Categorys{UserId: cs.UserId, CateName: "默认"}
        if err := helper.Db.Where(&category).First(&category).Error; err != nil {
            if errors.Is(err, gorm.ErrRecordNotFound) {
                return errors.New("分类不存在")
            }
            return err
        }
        cs.CategoryId = category.Id
    }
    collect := model.Collects{
        UserId: cs.UserId,
        CategoryId: cs.CategoryId,
        Title: cs.Title,
        Description: cs.Description,
        Content: cs.Content,
        ContentType: cs.ContentType,
    }
    collect.Status = enum.STATUS_ENABLED
    if err := helper.Db.Create(&collect).Error; err != nil {
        return err
    }
    // 触发添加收藏事件， 异步处理文件下载等逻辑
    helper.EventTrigger(enum.EVENT_CREATE_COLLECT, collect.Id, "")
    return nil
}

func (cs *CollectService) Update() error {
    if cs.Id == 0 {
        return errors.New("参数错误")
    }
    collect := model.Collects{Id: cs.Id}
    collect.Status = enum.STATUS_ENABLED
    if err := helper.Db.Where(&collect).First(&collect).Error; err != nil {
        if errors.Is(err, gorm.ErrRecordNotFound) {
            return errors.New("收藏记录不存在")
        }
        return err
    }
    if cs.CategoryId > 0 {
        collect.CategoryId = cs.CategoryId
    }
    if len(cs.Title) > 0 {
        collect.Title = cs.Title
    }
    if len(cs.Description) > 0 {
        collect.Description = cs.Description
    }
    if len(cs.Content) > 0 {
        collect.Content = cs.Content
    }
    if err := helper.Db.Updates(&collect).Error; err != nil {
        return err
    }
    // 触发添加收藏事件， 异步处理文件下载等逻辑
    var params string
    if paramsBytes, err := json.Marshal(collect); err != nil {
        return err
    } else {
        params = string(paramsBytes)
    }
    helper.EventTrigger(enum.EVENT_CREATE_COLLECT, collect.Id, params)
    return nil
}
